package com.wkh.common.http

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class HttpHelper {

    companion object {

        var HOST_NAME = "https://api.github.com/"

        var DEFAULT = "default_retrofit"

        private var instance: HttpHelper? = null
            get() {
                if (field == null) {
                    field = HttpHelper()
                }
                return field
            }

        @Synchronized
        fun get(): HttpHelper {
            return instance!!
        }
    }

    //网络连接超时
    private val defaultTimeOut = 10L

    private var retrofitMap = HashMap<String, CustomRetrofit>()

    fun getRetrofit(): CustomRetrofit {

        if (retrofitMap[DEFAULT] == null) {
            var okHttpClient = OkHttpClient
                .Builder()
                .connectTimeout(defaultTimeOut, TimeUnit.SECONDS)
                .readTimeout(defaultTimeOut, TimeUnit.SECONDS)
                .writeTimeout(defaultTimeOut, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build()

            var retrofit2 = Retrofit
                .Builder()
                .baseUrl(HOST_NAME)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

            var customRetrofit = CustomRetrofit(retrofit2)
            retrofitMap[DEFAULT] = customRetrofit
        }

        return getRetrofit(DEFAULT)
    }

    fun initCustomRetrofit(key: String, init: CustomHttpInit) {

        if (retrofitMap.containsKey(key)) {
            throw Exception("已有相同名称的retrofit初始化，请检查")
        }

        var customRetrofit = CustomRetrofit(init.initRetrofit())
        retrofitMap[key] = customRetrofit
    }

    fun getRetrofit(key: String): CustomRetrofit {
        if (!retrofitMap.containsKey(key) || retrofitMap[key] == null) {
            throw Exception("请先初始化retrofit：$key")
        }
        return retrofitMap[key]!!
    }


    /**
     * 对retrofit进行装饰
     */
    class CustomRetrofit(retrofit: Retrofit) {

        private var retrofit = retrofit

        private var serviceMap = HashMap<String, Any>()

        fun <S> getService(service: Class<S>): S {
            return if (serviceMap.containsKey(service.name)) {
                serviceMap[service.name] as S
            } else {
                var result: S? = null
                synchronized(this) {
                    result =
                        retrofit.create(service) ?: throw Exception("retrofit Exception")
                    serviceMap.put(service.name, result!!)
                }
                result!!
            }
        }
    }
}